import {isNumber, toNum} from '@utils/base'
export const length = len => function (val, model) {
  maxLength(len).call(this, val, model)
  val = this[model]
  return !!val && val.toString().length === len
}

export const minLength = min => val => !!val && val.length >= min

export const maxLength = max => function (val, model) {
  if (val == null) return false
  val = val.toString()
  if (val.length > max) this[model] = this[model].toString().substr(0, max)
  return true
}

export const integer = (len, transform = true, max = true) => function (val, model) {
  const flag = !!len
  let valid = true
  if (isNumber(len)) valid = (max ? maxLength : length)(len).call(this, val, model)
  val = toNum(this[model] + '', false).replace(/\.\d*/, '')
  val = val === '' ? '' : transform ? ~~val : val
  return valid && flag === /-?\d+/.test(this[model] = val)
}

export const maxValue = max => function (val, model) {
  if (val == null) return false
  val = toNum(val)
  if (val > max) this[model] = max
  return true
}

export const minValue = min => function (val, model) {
  if (val == null) return false
  val = toNum(val)
  if (val < min) this[model] = min
  return true
}

export const mobile = flag => function (val, model) {
  maxLength(11).call(this, val, model)
  return !!flag === /^1\d{10}$/.test(this[model])
}
